<template>
  <div class="container">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基础组件库" name="first">
        <h4>Element Plus组件</h4>
        <div class="basic-source">
          <draggable
            tag="ul"
            :list="basicSource"
            :component-data="{ sourceType: 'ElementPlus' }"
            item-key="key"
            :group="{ name: 'dragGroup', pull: 'clone', put: false }"
            :clone="handleContainerWidgetClone"
            ghost-class="ghost"
            :sort="false"
            :move="checkContainerMove"
            @end="onContainerDragEnd"
          >
            <template #item="{ element: ctn }">
              <li class="container-widget-item" title="组件名字">
                <span>
                  <el-icon><i-ep-Guide /></el-icon>
                  {{ ctn.text }}
                </span>
              </li>
            </template>
          </draggable>
        </div>
        <el-divider border-style="dotted" />
        <h4>业务组件</h4>
        <div class="basic-source">
          <draggable
            tag="ul"
            :list="busySource"
            item-key="key"
            :component-data="{ sourceType: 'Business' }"
            :group="{ name: 'dragGroup', pull: 'clone', put: false }"
            :clone="handleContainerWidgetClone"
            ghost-class="ghost"
            :sort="false"
            :move="checkContainerMove"
            @end="onContainerDragEnd"
          >
            <template #item="{ element: ctn }">
              <li class="container-widget-item" title="组件名字">
                <span>
                  <el-icon><i-ep-Guide /></el-icon>
                  {{ ctn.text }}
                </span>
              </li>
            </template>
          </draggable>
        </div>

        <el-divider border-style="dotted" />
        <h4>大屏组件</h4>
        <div
          style="
            height: 100px;
            border: 1px solid #e4e7ed;
            margin-top: 10px;
            padding: 10px;
            border-radius: 5px;
          "
        >
          <el-button type="primary" plain size="small">
            <el-icon><i-ep-Guide /></el-icon>输入框
          </el-button>
        </div>
        <el-divider border-style="dotted" />
        <h4>图表组件</h4>
        <div
          style="
            height: 100px;
            border: 1px solid #e4e7ed;
            margin-top: 10px;
            padding: 10px;
            border-radius: 5px;
          "
        >
          <el-button type="primary" plain size="small">
            <el-icon><i-ep-Guide /></el-icon>输入框
          </el-button>
        </div>
        <el-divider border-style="dotted" />
        <h4>3D组件</h4>
        <div
          style="
            height: 100px;
            border: 1px solid #e4e7ed;
            margin-top: 10px;
            padding: 10px;
            border-radius: 5px;
          "
        >
          <el-button type="primary" plain size="small">
            <el-icon><i-ep-Guide /></el-icon>输入框
          </el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="AI智能页面" name="second">
        <el-input
          v-model="aiInput"
          type="textarea"
          :rows="6"
          placeholder="如：生成考试系统页面..."
        ></el-input>

        <el-divider border-style="dotted" />
        <h4>根据描述信息，获取需要的JSON信息 , ....</h4>
        <div class="mt-2">
          <el-button type="primary" :loading="aiLoading" @click="testDeepSeek">
            DeepSeek-V3-0324
          </el-button>
          <el-button v-if="resultContent" type="primary" @click="useAiJson">采用</el-button>
        </div>
        <div class="preserve-newlines">
          {{ resultContent }}
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup name="SourcePanel">
import { sourceConfig } from '@/views/LowDesigner/source-config.ts'
import { computed, ref } from 'vue'
import { askDeepseek } from '@/service/low-code'

const emits = defineEmits(['jsonLoad'])

const aiInput = ref('')
const activeName = ref('first')
const basicSource = computed(() => {
  const module: any = sourceConfig.find((item) => item.sourceType === 'ElementPlus')
  return module.widgetList
})

const busySource = computed(() => {
  const module: any = sourceConfig.find((item) => item.sourceType === 'Business')
  return module.widgetList
})

const handleContainerWidgetClone = () => {}

// 当draggable中的元素，被拖到了另一个draggable中时，会触发此方法
const checkContainerMove = (evt: any) => {
  //
  let wgCategory = evt.draggedContext.element.category // 被拖动的元素是什么
  let wgType = evt.draggedContext.element.type // 被拖动的元素是什么类型

  let toClassName = evt.to.className // 接收方是什么元素。

  // 这里对 什么元素可以被拖到什么元素中去，进行定义判断。 默认都是可以的 return true;
  // 如果不能拖动，则return false;
  // 如：
  if (!!evt.to) {
    if (toClassName === 'sub-from-drag-drop' && wgCategory === 'container') {
      return false
    }
  }
  return true
}

/**
 * 当其他draggable中的元素被拖动到此draggable中时，会触发此方法，
 * 这里是发出方，所以不做操作
 */
const onContainerDragEnd = () => {}

const aiLoading = ref(false)
const resultContent = ref('')
async function testDeepSeek() {
  aiLoading.value = true
  const result = await askDeepseek(aiInput.value).finally(() => {
    aiLoading.value = false
  })
  if (result.code === 200) {
    resultContent.value = result.data
  } else {
    resultContent.value = result.message
  }
}

function extractAndParseJSON(str: string) {
  // 定义正则表达式模式，用于匹配 ```json 和 ``` 之间的内容
  const jsonPattern = /```json\s*([\s\S]*?)\s*```/

  // 执行匹配
  const match = str.match(jsonPattern)

  // 如果没有找到匹配项，返回null
  if (!match || match.length < 2) {
    return null
  }

  // 获取捕获组中的JSON字符串
  const jsonStr = match[1].trim()

  try {
    // 尝试解析JSON字符串
    const parsedJSON = JSON.parse(jsonStr)
    return parsedJSON
  } catch (e) {
    // 如果解析失败，记录错误并返回null
    console.error('JSON解析失败:', e)
    return null
  }
}

function useAiJson() {
  const jsonData = extractAndParseJSON(resultContent.value)
  console.log('jsonData', jsonData)
  emits('jsonLoad', jsonData[0])
}
</script>

<style lang="scss" scoped>
.container {
  /* border: 1px solid red; */
}
.basic-source {
  height: 100px;
  border: 1px solid #e4e7ed;
  margin-top: 10px;
  padding: 10px;
  border-radius: 5px;
}

.basic-source::v-deep(ul) {
  padding-left: 10px; /* 重置IE11默认样式 */
  margin: 0; /* 重置IE11默认样式 */
  margin-block-start: 0;
  margin-block-end: 0.25em;
  padding-inline-start: 10px;

  &:after {
    content: '';
    display: block;
    clear: both;
  }

  .container-widget-item,
  .field-widget-item,
  .chart-container-widget-item,
  .chart-widget-item {
    //text-align: center; // 居中显示不太美观
    display: inline-block;
    height: 32px;
    line-height: 32px;
    width: 120px;
    float: left;
    margin: 2px 6px 6px 0;
    cursor: move;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 8px;
  }

  .container-widget-item:hover,
  .field-widget-item:hover,
  .chart-container-widget-item:hover,
  .chart-widget-item:hover {
    background: #f1f2f3;
    border-color: red;

    .color-svg-icon {
      color: red;
    }
  }

  .chart-container-widget-item,
  .chart-widget-item {
    cursor: default !important;
  }

  .drag-handler {
    position: absolute;
    top: 0;
    left: 160px;
    background-color: #dddddd;
    border-radius: 5px;
    padding-right: 5px;
    font-size: 11px;
    color: #666666;
  }
}
.preserve-newlines {
  white-space: pre-wrap; /* 保留空白符序列，不过正常地进行换行 */
}
</style>
